package com.stox.services.indicator.model.intf;

import java.util.List;

import org.springframework.stereotype.Component;

import com.stox.services.indicator.model.config.SpanOnlyConfig;
import com.stox.shared.indicator.model.IndicatorBeanDescriptor;
import com.stox.shared.indicator.model.enumeration.IndicatorPosition;
import com.stox.shared.model.Bar;

@Component
public class SimpleMovingAverageVolume implements
		Indicator<Double, SpanOnlyConfig> {

	private final IndicatorBeanDescriptor indicatorBeanDescriptor = new IndicatorBeanDescriptor(
			createDefaultConfiguration(),
			"SimpleMovingAverageVolume",
			IndicatorPosition.OVERLAY_VOLUME,
			Double.class);
	
	@Override
	public Double getValue(SpanOnlyConfig configuration, Double[] in, int index)
			throws UnsupportedOperationException {
		double sum = 0;
		int span = configuration.getSpan();
		for(int i = index; i < index + span; i++){
			sum += in[index];
		}
		return sum/span;
	}

	@Override
	public Double getValue(SpanOnlyConfig configuration, List<Bar> bars,
			int index) {
		return getValue(configuration, asDoubleArray(bars), index);
	}

	@Override
	public Double[] getValues(SpanOnlyConfig configuration, Double[] values)
			throws UnsupportedOperationException {
		Double[] result = new Double[values.length];
		double sum = 0;
		int span = configuration.getSpan();
		int size = values.length;
		for(int i = size - 1; i >= 0; i--){
			if(null == values[i]) continue;
			sum += values[i];
			if(i > size - 1 - span) continue;
			if(null == values[i + span]) continue;
			sum -= values[i + span];
			result[i] = sum/span;
		}
		return result;
	}

	@Override
	public Double[] getValues(SpanOnlyConfig configuration, List<Bar> bars) {
		return getValues(configuration, asDoubleArray(bars));
	}

	protected Double[] asDoubleArray(List<Bar> bars){
		Double[] result = new Double[bars.size()];
		for(int index = 0; index < result.length; index++){
			result[index] = bars.get(index).getVolume();
		}
		return result;
	}
	
	@Override
	public SpanOnlyConfig createDefaultConfiguration() {
		return new SpanOnlyConfig();
	}

	@Override
	public IndicatorBeanDescriptor getIndicatorBeanDescriptor() {
		return indicatorBeanDescriptor;
	}

}
